import { is } from 'immutable';
import { message } from 'antd'
import { browserHistory,hashHistory } from 'react-router';
import * as fetch from './fetch';

import { getFile_IP } from './serverIp'

export const utils = {
    test() {
        console.log('test ok')
    }
}
export const jumpHistory = hashHistory;

export let user = JSON.parse(localStorage.getItem('user'));

export const save_user = () => {
    user = JSON.parse(localStorage.getItem('user'));
}

export const checkldToken = () => {
    let now_timestamp = Date.parse(new Date());
    let min = (user.deadTime - now_timestamp) / (60 * 1000);
    if (min < 10) {
        fetch.refreshTken().then((data) => {
            if (data.result === 'RC100') {
                let user = JSON.parse(localStorage.getItem('user'));
                user.deadTime = data.deadTime;
                user.ldToken = data.ldToken;
                localStorage.setItem("ldToken", data.ldToken);
                localStorage.removeItem('user');
                localStorage.setItem("user", JSON.stringify(user));
                save_user();
            } else {
                message.error(data.errMsg, 3);
            }
        }, (res) => {
            reject(res);
        })
    }
}


export const exit = () => {
    jumpHistory.push('/Login');
    localStorage.removeItem('user');

    fetch.loginOut().then((data) => {
        if (data.result === 'RC100') {

        } else {
            message.error(data.errMsg, 3);
        }
    }, (res) => {

    })
}

export const behavior = (body, operationType, behaviorDataType) => {
    return Object.assign(body, {
        operationTypes: operationType,
        behaviorDataType: behaviorDataType,
        ldToken: localStorage.getItem('ldToken'),
        userCode: user ? user.userCode : '',
        deviceId: '',
        netType: '',
        operationLocation: '',
    })
}
export const getPaperId = (text) => {

    let index = text.indexOf('id:');
    if (index === -1) {
        return false;
    }
    return text.slice(index + 1, text.length)
};

export const url_parameter = (data) => {

    var toString = "";
    for (var key in data) {
        var obj = data[key];
        if (Array.isArray(obj)) {
            var arrayString = obj.join(",");
            toString += key + "=" + arrayString + "&";
        } else {
            toString += key + "=" + data[key] + "&";
        }
    }
    return toString.replace(/$/, "");
}
export const url_format = (url, operationType, behaviorDataType) => {
    return url + '?' + url_parameter(behavior({}, operationType, behaviorDataType));
}
export const getFile = (fileName) => {
    if (fileName === null || fileName === undefined) {
        return 'error_path';
    }
    return url_format(getFile_IP + fileName);
}
export const getAnswer = (num) => {
    let answer = []
    switch (num) {
    case 1:
        answer = [0];
        break;
    case 2:
        answer = [1];
        break;
    case 4:
        answer = [2];
        break;
    case 8:
        answer = [3];
        break;
    case 3:
        answer = [0, 1];
        break;
    case 5:
        answer = [0, 2];
        break;
    case 9:
        answer = [0, 3];
        break;
    case 6:
        answer = [1, 2];
        break;
    case 10:
        answer = [1, 3];
        break;
    case 12:
        answer = [2, 3];
        break;
    case 7:
        answer = [0, 1, 2];
        break;
    case 11:
        answer = [0, 1, 3];
        break;
    case 13:
        answer = [0, 2, 3];
        break;
    case 14:
        answer = [1, 2, 3];
        break;
    case 15:
        answer = [0, 1, 2, 3];
        break;
    default:
        break;
    }
    return answer;
}

/*
get Object to map
 */
export const getObject = (num) => {
    let obj = [];
    for (let i = 0; i < num; i++) {
        obj.push({})
    }
    return obj;
}
// new RegExp('-', "g" )
/*
format timestamp
 */
export const formatTimestamp = (timestamp, type) => {
    let now = new Date(timestamp);
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minute = now.getMinutes();
    let second = now.getSeconds();
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    hour = hour < 10 ? "0" + hour : hour;
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;
    if (type === 'y-m-d') {
        return year + "-" + month + "-" + day;
    }
    if (type === 'y-m-d h-m') {
        return year + "-" + month + "-" + day + " " + hour + ":" + minute;
    }
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}

export const reject = (res) => {
    if (res.status === 499) {
        message.error('请求超时,请检查网络', 3);
    } else {
        message.error(res.status + ': 请求失败,请检查服务器', 3);
    }
}
export const headImageError = (e) => {
    e.target.src = require('../style/images/portrait.png');
}
export const courseTypeList = ['销售类', '管理类', '科学类'];
// export let courseTypeList = [];
export const courseChannel = ['内勤', '个险', '团险', '', '银保', '续期'];

/*
get today date
 */
export const getToday = () => {
    let date = new Date();
    // let Y = date.getFullYear();
    let M = date.getMonth() + 1;
    let D = date.getDate();
    M = M < 10 ? '0' + M : M;
    D = D < 10 ? '0' + D : D;

    let today = M + '月' + D + '日';
    return today;
}

/*
get local IP
 */
export const getIp = () => {

    // return new Promise((resolve, reject) => {
    //    $.ajax({
    //         url: 'https://api.ipify.org',
    //         type: 'GET',
    //    })
    //    .done(function(data) {
    //         console.log("success",data);
    //    })
    //    .fail(function() {
    //         console.log("error");
    //    })
    //    .always(function() {
    //         // console.log("complete");
    //    });

    // });

}

export const queryString = () => {
    let _queryString = {};
    const _query = window.location.search.substr(1);
    const _vars = _query.split('&');
    _vars.forEach((v, i) => {
        const _pair = v.split('=');
        if (!_queryString.hasOwnProperty(_pair[0])) {
            _queryString[_pair[0]] = decodeURIComponent(_pair[1]);
        } else if (typeof _queryString[_pair[0]] === 'string') {
            const _arr = [_queryString[_pair[0]], decodeURIComponent(_pair[1])];
            _queryString[_pair[0]] = _arr;
        } else {
            _queryString[_pair[0]].push(decodeURIComponent(_pair[1]));
        }
    });
    return _queryString;
};

/*
show loading
 */
export const loading = (_this, flag) => {
    _this.setState({
        loading: flag
    })
}
export const loadBtning = (_this, flag) => {
    _this.setState({
        loadBtning: flag
    })
}
export const getRandomColor = () => {
    return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
export const Main = {
    /**
     * 本地数据存储或读取
     * 
     * @param {any} key
     * @param {any} value
     * @returns
     */
    localItem(key, value) {
        if (arguments.length === 1) {
            return localStorage.getItem(key) && localStorage.getItem(key) !== 'null' ? localStorage.getItem(key) : null;
        } else {
            return localStorage.setItem(key, value);
        }
    },
    /**
     * 删除本地数据
     * 
     * @param {any} k
     * @returns
     */
    removeLocalItem(key) {
        if (arguments.length === 1) {
            return localStorage.removeItem(key);
        } else {
            return localStorage.clear();
        }
    }
}
/**
 * 代码优化
 * by QianLi
 * 2017-8-24
 */
export const shouldComponentUpdate = (nextProps = {}, nextState = {}, thisProps = {}, thisState = {}) => {
    if (Object.keys(thisProps).length !== Object.keys(nextProps).length) {
        return true;
    }
    if (thisState && nextState && Object.keys(thisState).length !== Object.keys(nextState).length) {
        return true;
    }
    for (const key in nextProps) {
        if (thisProps[key] !== nextProps[key] || !is(thisProps[key], nextProps[key])) {
            return true;
        }
    }
    for (const key in nextState) {
        if (thisState[key] !== nextState[key] || !is(thisState[key], nextState[key])) {
            return true;
        }
    }
    return false;
}
export const checkLogin = (data) => {
    if (data.result === "RC500") {
        jumpHistory.push('/Login');
        message.error(data.errMsg, 3);
    }
}
/**
 * 文章显示
 */
export const subString = (string, subLength) => {
    if (typeof (string) !== 'string') {
        return '';
    }
    if (string.length > subLength) {
        return string.substring(0, subLength) + '...'
    } else {
        return string
    }
}